#include "node.h"

void node::clean(){
    for(auto& child : children_){
        child->clean();
        delete child;
        child = nullptr;
    }
    children_.clear();
}

void node::render(){
    for(auto& child : children_){
        if(child->isActive()){
            //SDL_Log("node %s render",child->name_.c_str());
            child->render();
        }
    }
}

void node::update(float dt){
    
    for(auto& child : to_add){
        //SDL_Log("to_add size:%d",to_add.size());
        //SDL_Log("children_ size:%d",children_.size());
        //SDL_Log("safe add child node name:%s add",child->name_.c_str());
        addChild(child);
    }
    to_add.clear();
        //SDL_Log("to_add size:%d",to_add.size());
    for(auto it  = children_.begin(); it != children_.end();){
        auto child = *it;
        //SDL_Log("node update name:%s",child->name_.c_str());
        if(child->getNeedRemove()){
            //SDL_Log("child node Remove");
            it = children_.erase(it);
            child->clean();
        }else{
            if(child->isActive()){
            //SDL_Log("node name:%s update %d",child->name_.c_str(),child->isActive());
                child->update(dt);
            }
            ++it;
        }
        //SDL_Log("child node name:%s end",child->name_.c_str());
    }
}

bool node::handleEvents(SDL_Event& event){
    for(auto& child : children_){
        if(child->isActive()){
            //SDL_Log("child node name:%s end",child->name_.c_str());
            if(child->handleEvents(event))
                return true;
        }
    }
    return false;
}
